package cn.lcc;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {

    /*
        根据返回字符串  决定当前自己定义的这个过滤器是什么类型
     */
    @Override
    public String filterType() {
        return "pre";
    }
    /*
        同种类型过滤器的执行顺序
     */
    @Override
    public int filterOrder() {
        return 1;
    }
    /*
        true: 执行调用  run（）
        false: 不会调用执行 run()

     */
    @Override
    public boolean shouldFilter() {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //2.获取url uri
        System.out.println(request.getRequestURI());
        // System.out.println(request.getRequestURL());
        String uri = request.getRequestURI();
        //直接放行的逻辑
        if (uri.endsWith("/login")||uri.endsWith("/reg")||uri.contains("/static/")){
            return  false;
        }
        //执行下面的run（）
        return true;
    }
    @Override
    public Object run() throws ZuulException {
        //权限检查的核心代码
        //1.拿到请求头
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //2.获取token 请求头
        String token = request.getHeader("token");
        //3.验证token
        if(token==null||token.length()==0){
            //4.返回错误的提示数据
            //告诉浏览器：我给你响应一个json数据，并且使用UTF-8进行编码
            response.setContentType("application/json;charset=UTF-8");
            //由于上面已经告诉了浏览器指定的类型。所以浏览器接收到这个数据之后就会自动转换成json对象
            try {
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.2.阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        //.... 对应的检查
        return null;
    }
}